﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Controls.Pivot;
using Microsoft.SharePoint.Client;
using System.ComponentModel;
using System.IO;
using System.Xml.Linq;
using System.Windows.Browser;
using System.Threading;

namespace PivotViewerSL
{
    public class SPItemSource : INotifyPropertyChanged
    {
        private string _webUrl;
        public SPItemSource()
        {
            _webUrl = ((App)App.Current).WebUrl;
        }
        public string FileType { get; set; }
        public string Title { get; set; }
        public DateTime Created { get; set; }
        public string Author { get; set; }
        public DateTime Modified { get; set; }
        public int FileSize { get; set; }
        public Uri Url { get; set; }
        private Microsoft.SharePoint.Client.File _file;
        public Microsoft.SharePoint.Client.File File
        {
            get
            {
                return _file;
            }
            set
            {
                _file = value;
                ClientContext ctx =  new ClientContext(_webUrl);
                switch (System.IO.Path.GetExtension(File.Name))
                {
                    case ".docx":
                        try
                        {
                            getDocImage(_file.ServerRelativeUrl);
                        }
                        catch
                        {
                            _iconLarge = ctx.Url + "/_layouts/images/icdocx.png";
                            _iconMedium = ctx.Url + "/_layouts/images/icdocx.png";
                            _iconLittle = ctx.Url + "/_layouts/images/icdocx.png";
                        }
                        break;
                    case ".pptx":
                    case ".ppt":
                        try
                        {
                            getPptImage(_file.ServerRelativeUrl);
                        }
                        catch 
                        {
                            _iconLarge = ctx.Url + "/_layouts/images/icpptx.png";
                            _iconMedium = ctx.Url + "/_layouts/images/icpptx.png";
                            _iconLittle = ctx.Url + "/_layouts/images/icpptx.png";
                        }
                        break;
                    default:
                        ClientResult<string> Icon = ctx.Web.MapToIcon(_file.Name, "", Microsoft.SharePoint.Client.Utilities.IconSize.Size16);
                        ctx.ExecuteQuery();
                         _iconLarge  = Icon.Value;
                         _iconMedium = Icon.Value;
                         _iconLittle = Icon.Value;
                        break;
                }

            }
        }
        private string strUrlImage;
        private string strUrlDocXml;
        int pageCount;

        private string _iconLarge = "/_layouts/images/icdocx.png";
        private string _iconMedium = "/_layouts/images/icdocx.png";
        private string _iconLittle = "/_layouts/images/icdocx.png";
        public string IconLarge
        {
            get
            {

                return _iconLarge;
            }

        }
        public string IconMedium
        {
            get
            {

                return _iconMedium;
            }

        }
        public string IconLittle
        {
            get
            {

                return _iconLittle;
            }

        }
        public void getPptImage(string pptUrl)
        {
            BackgroundWorker worker = new BackgroundWorker();
            ManualResetEvent waiter = new ManualResetEvent(false);
            worker.DoWork += (s, e) =>
                {
                    try
                    {
                        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(_webUrl + "/_layouts/MobilePresentation.ashx?presentationId=" + HttpUtility.UrlEncode(pptUrl));
                        request.UseDefaultCredentials = true;
                        request.BeginGetResponse((asynchronousResult) =>
                        {
                            try
                            {
                                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
                                using (StreamReader streamReader1 = new StreamReader(response.GetResponseStream()))
                                {
                                    string resultString = streamReader1.ReadToEnd();
                                    XDocument xdoc = XDocument.Parse(resultString);

                                    string strImageUrl = xdoc.Element(XName.Get("mobilePres", "http://schemas.microsoft.com/server/powerpoint/2009/mobile")).Element(XName.Get("slideImage", "http://schemas.microsoft.com/server/powerpoint/2009/mobile")).Attribute("url").Value;

                                    XElement xImageSLD = xdoc.Element(XName.Get("mobilePres", "http://schemas.microsoft.com/server/powerpoint/2009/mobile")).Element(XName.Get("pres", "http://schemas.microsoft.com/server/powerpoint/2009/mobile")).Element(XName.Get("sldLst", "http://schemas.microsoft.com/server/powerpoint/2009/mobile"));

                                    foreach (XElement el in xImageSLD.Elements(XName.Get("sld", "http://schemas.microsoft.com/server/powerpoint/2009/mobile")))
                                    {
                                        string strImageID = el.Attribute("sldImg").Value;
                                        string strUrlLarge = _webUrl + "/_layouts/" + strImageUrl + "&imageId=" + strImageID + "&width=320&height=240";
                                        string strUrlMedium = _webUrl + "/_layouts/" + strImageUrl + "&imageId=" + strImageID + "&width=160&height=120";
                                        string strUrlLittle = _webUrl + "/_layouts/" + strImageUrl + "&imageId=" + strImageID + "&width=80&height=60";
                                        WarmImage(strUrlLarge);
                                        WarmImage(strUrlMedium);
                                        WarmImage(strUrlLittle);
                                        _iconLarge = strUrlLarge;
                                        _iconMedium = strUrlMedium;
                                        _iconLittle = strUrlLittle;
                                        NotifyPropertyChanged("IconLarge");
                                        NotifyPropertyChanged("IconMedium");
                                        NotifyPropertyChanged("IconLittle");
                                        break;

                                    }

                                }
                            }
                            catch {
                                _iconLarge = _webUrl + "/_layouts/images/icpptx.png";
                                _iconMedium = _webUrl + "/_layouts/images/icpptx.png";
                                _iconLittle = _webUrl + "/_layouts/images/icpptx.png";
                            }

                            waiter.Set();


                        }, request);
                    }
                    catch
                    {
                        _iconLarge = _webUrl + "/_layouts/images/icpptx.png";
                        _iconMedium = _webUrl + "/_layouts/images/icpptx.png";
                        _iconLittle = _webUrl + "/_layouts/images/icpptx.png";
                    }
                };
            worker.RunWorkerAsync();
            waiter.WaitOne();
        }

        private void getDocImage(string docUrl)
        {
            HttpWebRequest request;

            request = (HttpWebRequest)HttpWebRequest.Create(_webUrl + "/_layouts/MobileDocHandler.ashx?doc=" + HttpUtility.UrlEncode(docUrl));
            request.BeginGetResponse((asynchronousResult) =>
            {
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
                using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
                {
                    string resultString = streamReader.ReadToEnd();
                    XDocument xdoc = XDocument.Parse(resultString);
                    strUrlImage = xdoc.Element("mobileDoc").Element("pageImage").Attribute("url").Value;
                    strUrlDocXml = xdoc.Element("mobileDoc").Element("pageXml").Attribute("url").Value;
                    pageCount = int.Parse(xdoc.Element("mobileDoc").Element("document").Element("pageset").Attribute("count").Value);
                    HttpWebRequest requestDocXML = (HttpWebRequest)HttpWebRequest.Create(_webUrl + "/_layouts/" + strUrlDocXml + "&n=p_1_10.xml");
                    requestDocXML.BeginGetResponse((asynchronousResult1) =>
                    {
                        HttpWebResponse responseDocXml = (HttpWebResponse)requestDocXML.EndGetResponse(asynchronousResult1);
                        using (StreamReader streamReader1 = new StreamReader(responseDocXml.GetResponseStream()))
                        {
                            string resultStringXml = streamReader1.ReadToEnd();
                            XDocument xdocXml = XDocument.Parse(resultStringXml);
                            string firstPageID = xdocXml.Element("Pages").Element("Page").Element("P").Element("L").Element("LT").Attribute("p").Value;
                            int PageID = int.Parse(firstPageID);
                            string strUrlLarge = _webUrl + "/_layouts/" + strUrlImage + "&n=p" + PageID + ".img&width=210&height=297";
                            string strUrlMedium = _webUrl + "/_layouts/" + strUrlImage + "&n=p" + PageID + ".img&width=140&height=198";
                            string strUrlLittle = _webUrl + "/_layouts/" + strUrlImage + "&n=p" + PageID + ".img&width=70&height=99";
                            WarmImage(strUrlLarge);
                            WarmImage(strUrlMedium);
                            WarmImage(strUrlLittle);
                            _iconLarge = strUrlLarge;
                            _iconMedium = strUrlMedium;
                            _iconLittle = strUrlLittle;
                            NotifyPropertyChanged("IconLarge");
                            NotifyPropertyChanged("IconMedium");
                            NotifyPropertyChanged("IconLittle");
                        }

                    }
                    , requestDocXML);
                }


            }
                , request);

        }

        private void WarmImage(string strUrlLarge)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(strUrlLarge);
            request.BeginGetResponse((asynchronousResult) =>
            {
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
                using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
                {
                }
            },request);
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

    }
}
